package com.zohnmall.member.service.impl;

import com.zohnmall.member.dao.MemberDao;
import com.zohnmall.member.dao.MemberLevelDao;
import com.zohnmall.member.entity.MemberLevelEntity;
import com.zohnmall.member.exception.PhoneException;
import com.zohnmall.member.exception.UsernameException;
import com.zohnmall.member.vo.MemberLoginVo;
import com.zohnmall.member.vo.MemberRegistVo;
import com.zohnmall.member.vo.SocialUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.Map;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zohnmall.common.utils.PageUtils;
import com.zohnmall.common.utils.Query;

import com.zohnmall.member.entity.MemberEntity;
import com.zohnmall.member.service.MemberService;


@Service("memberService")
public class MemberServiceImpl extends ServiceImpl<MemberDao, MemberEntity> implements MemberService {

    @Autowired
    MemberLevelDao memberLevelDao;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<MemberEntity> page = this.page(
                new Query<MemberEntity>().getPage(params),
                new QueryWrapper<MemberEntity>()
        );

        return new PageUtils(page);
    }


    @Override
    public void regist(MemberRegistVo vo) {
        MemberDao memberDao = this.baseMapper;
        MemberEntity memberEntity = new MemberEntity();

        // 设置默认等级
        MemberLevelEntity levelEntity = memberLevelDao.getDefaultLevel();
        memberEntity.setLevelId(levelEntity.getId());

        // 检查用户名和手机号是否唯一.为了让controller能感到异常，异常机制
        checkPhoneUnique(vo.getPhone());
        checkUsernameUnique(vo.getUserName());

        memberEntity.setMobile(vo.getPhone());
        memberEntity.setUsername(vo.getUserName());

        memberEntity.setNickname(vo.getUserName());

        // 密码要加密存储
        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        String encode = passwordEncoder.encode(vo.getPassword());
        memberEntity.setPassword(encode);

        // 其他的默认信息

        // 保存
        memberDao.insert(memberEntity);
    }

    /**
     * 判断手机号是否存在
     *
     * @param phone
     * @throws PhoneException
     */
    @Override
    public void checkPhoneUnique(String phone) throws PhoneException {
        MemberDao memberDao = this.baseMapper;
        Integer mobile = memberDao.selectCount(new QueryWrapper<MemberEntity>().eq("mobile", phone));
        if (mobile > 0) {
            throw new PhoneException();
        }

    }

    /**
     * 判断用户名是否存在
     *
     * @param username
     * @throws UsernameException
     */
    @Override
    public void checkUsernameUnique(String username) throws UsernameException {
        MemberDao memberDao = this.baseMapper;
        Integer count = memberDao.selectCount(new QueryWrapper<MemberEntity>().eq("username", username));
        if (count > 0) {
            throw new UsernameException();
        }
    }

    @Override
    public MemberEntity login(MemberLoginVo vo) {
        String loginAcct = vo.getLoginAcct();
        String password = vo.getPassword();

        // 1、去数据库查询 SELECT * FROM ums_member WHERE username = ? OR mobile = ?
        MemberDao memberDao = this.baseMapper;
        MemberEntity entity = memberDao.selectOne(new QueryWrapper<MemberEntity>().eq("username", loginAcct).
                or().eq("mobile", loginAcct));
        if(entity == null) {
            // 登录失败
            return null;
        } else {
            // 1、获取到数据库的password
            String passwordDb = entity.getPassword();
            BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
            // 2、进行密码匹配
            boolean matches = passwordEncoder.matches(password, passwordDb);
            if(matches) {
                return entity;
            } else {
                return null;
            }
        }
    }

    @Override
    public MemberEntity login(SocialUser socialUserGitee) {
        // 登录和注册合并逻辑
        String uid = socialUserGitee.getUid();
        // 1、判断当前社交用户的是否已经登录过系统
        MemberDao memberDao = this.baseMapper;
        MemberEntity memberEntity = memberDao.selectOne(new QueryWrapper<MemberEntity>().eq("social_uid", uid));
        if(memberEntity != null) {
            // 这个用户已经注册
            MemberEntity update = new MemberEntity();
            update.setId(memberEntity.getId());
            update.setAccessToken(socialUserGitee.getAccess_token());
            update.setExpiresIn(String.valueOf(socialUserGitee.getExpires_in()));
            memberDao.updateById(update);

            memberEntity.setAccessToken(socialUserGitee.getAccess_token());
            memberEntity.setExpiresIn(String.valueOf(socialUserGitee.getExpires_in()));
            return memberEntity;
        } else {
            // 2、没有查到当前社交用户对应的记录，需要注册一个
            MemberEntity regist = new MemberEntity();
            // 3、查询当前社交用户的社交账号信息（昵称，性别等）
            regist.setNickname(socialUserGitee.getName());
            regist.setSocialUid(socialUserGitee.getUid());
            regist.setAccessToken(socialUserGitee.getAccess_token());
            regist.setExpiresIn(String.valueOf(socialUserGitee.getExpires_in()));
            // 设置默认等级
            MemberLevelEntity levelEntity = memberLevelDao.getDefaultLevel();
            regist.setLevelId(levelEntity.getId());
            memberDao.insert(regist);
            return regist;
        }
    }

}